"use client"

import { useState, useEffect } from 'react'
import { textStyles } from '../../../lib/fontConfig'
import { useProgressManager } from '../../../lib/progressManager'

interface QuizGameProps {
  targetChar: string
  onGameEnd: (score: number, correct: number, total: number) => void
}

interface QuizQuestion {
  question: string
  options: string[]
  correctAnswer: number
  explanation: string
}

export function QuizGame({ targetChar, onGameEnd }: QuizGameProps) {
  const [currentQuestion, setCurrentQuestion] = useState<QuizQuestion | null>(null)
  const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null)
  const [showResult, setShowResult] = useState(false)
  const [score, setScore] = useState(0)
  const [correctAnswers, setCorrectAnswers] = useState(0)
  const [totalQuestions, setTotalQuestions] = useState(0)
  const [timeLeft, setTimeLeft] = useState(60)
  const [gameOver, setGameOver] = useState(false)
  const [questionIndex, setQuestionIndex] = useState(0)

  const { getCharacterProgress } = useProgressManager()

  // 生成问题
  const generateQuestion = (): QuizQuestion => {
    const questionTypes = [
      'strokes', 'meaning', 'pronunciation', 'radical', 'words'
    ]
    
    const type = questionTypes[Math.floor(Math.random() * questionTypes.length)]
    
    switch (type) {
      case 'strokes':
        return generateStrokeQuestion(targetChar)
      case 'meaning':
        return generateMeaningQuestion(targetChar)
      case 'pronunciation':
        return generatePronunciationQuestion(targetChar)
      case 'radical':
        return generateRadicalQuestion(targetChar)
      case 'words':
        return generateWordQuestion(targetChar)
      default:
        return generateStrokeQuestion(targetChar)
    }
  }

  // 笔画问题
  const generateStrokeQuestion = (char: string): QuizQuestion => {
    const strokeData: { [key: string]: number } = {
      '木': 4, '人': 2, '水': 4, '火': 4, '土': 3, '山': 3, '口': 3, '心': 4
    }
    
    const correctStrokes = strokeData[char] || 4
    const options = [
      correctStrokes.toString() + '画',
      (correctStrokes + 1).toString() + '画',
      (correctStrokes - 1).toString() + '画',
      (correctStrokes + 2).toString() + '画'
    ]
    
    // 打乱选项
    const shuffledOptions = shuffleArray(options)
    const correctIndex = shuffledOptions.indexOf(correctStrokes.toString() + '画')
    
    return {
      question: `"${char}"字有几画？`,
      options: shuffledOptions,
      correctAnswer: correctIndex,
      explanation: `"${char}"字共有${correctStrokes}画。`
    }
  }

  // 含义问题
  const generateMeaningQuestion = (char: string): QuizQuestion => {
    const meaningData: { [key: string]: { correct: string, wrong: string[] } } = {
      '木': { correct: '树木', wrong: ['石头', '河水', '火焰'] },
      '人': { correct: '人类', wrong: ['动物', '植物', '石头'] },
      '水': { correct: '液体', wrong: ['固体', '气体', '金属'] },
      '火': { correct: '火焰', wrong: ['冰块', '石头', '树叶'] },
      '土': { correct: '土地', wrong: ['天空', '海洋', '森林'] },
      '山': { correct: '山峰', wrong: ['河流', '平原', '沙漠'] }
    }
    
    const data = meaningData[char] || { correct: '树木', wrong: ['石头', '河水', '火焰'] }
    const options = [data.correct, ...data.wrong]
    const shuffledOptions = shuffleArray(options)
    const correctIndex = shuffledOptions.indexOf(data.correct)
    
    return {
      question: `"${char}"字的含义是什么？`,
      options: shuffledOptions,
      correctAnswer: correctIndex,
      explanation: `"${char}"字的含义是${data.correct}。`
    }
  }

  // 读音问题
  const generatePronunciationQuestion = (char: string): QuizQuestion => {
    const pronunciationData: { [key: string]: { correct: string, wrong: string[] } } = {
      '木': { correct: 'mù', wrong: ['mú', 'mǔ', 'mù'] },
      '人': { correct: 'rén', wrong: ['rèn', 'rěn', 'rēn'] },
      '水': { correct: 'shuǐ', wrong: ['shuí', 'shuì', 'shuī'] },
      '火': { correct: 'huǒ', wrong: ['huó', 'huò', 'huō'] },
      '土': { correct: 'tǔ', wrong: ['tú', 'tù', 'tū'] }
    }
    
    const data = pronunciationData[char] || { correct: 'mù', wrong: ['mú', 'mǔ', 'mù'] }
    const options = [data.correct, ...data.wrong.slice(0, 3)]
    const shuffledOptions = shuffleArray(options)
    const correctIndex = shuffledOptions.indexOf(data.correct)
    
    return {
      question: `"${char}"字的读音是？`,
      options: shuffledOptions,
      correctAnswer: correctIndex,
      explanation: `"${char}"字的正确读音是${data.correct}。`
    }
  }

  // 部首问题
  const generateRadicalQuestion = (char: string): QuizQuestion => {
    const radicalData: { [key: string]: { correct: string, wrong: string[] } } = {
      '木': { correct: '木字旁', wrong: ['水字旁', '火字旁', '土字旁'] },
      '人': { correct: '人字旁', wrong: ['木字旁', '口字旁', '心字旁'] },
      '水': { correct: '水字旁', wrong: ['木字旁', '火字旁', '人字旁'] },
      '火': { correct: '火字旁', wrong: ['水字旁', '木字旁', '土字旁'] }
    }
    
    const data = radicalData[char] || { correct: '木字旁', wrong: ['水字旁', '火字旁', '土字旁'] }
    const options = [data.correct, ...data.wrong]
    const shuffledOptions = shuffleArray(options)
    const correctIndex = shuffledOptions.indexOf(data.correct)
    
    return {
      question: `"${char}"字属于哪个部首？`,
      options: shuffledOptions,
      correctAnswer: correctIndex,
      explanation: `"${char}"字属于${data.correct}。`
    }
  }

  // 组词问题
  const generateWordQuestion = (char: string): QuizQuestion => {
    const wordData: { [key: string]: { correct: string, wrong: string[] } } = {
      '木': { correct: '树木', wrong: ['河水', '山火', '土地'] },
      '人': { correct: '人类', wrong: ['木头', '水流', '火焰'] },
      '水': { correct: '河水', wrong: ['树木', '火焰', '土地'] },
      '火': { correct: '火焰', wrong: ['河水', '树木', '土地'] }
    }
    
    const data = wordData[char] || { correct: '树木', wrong: ['河水', '山火', '土地'] }
    const options = [data.correct, ...data.wrong]
    const shuffledOptions = shuffleArray(options)
    const correctIndex = shuffledOptions.indexOf(data.correct)
    
    return {
      question: `下面哪个词语包含"${char}"字？`,
      options: shuffledOptions,
      correctAnswer: correctIndex,
      explanation: `"${data.correct}"包含"${char}"字。`
    }
  }

  // 打乱数组
  const shuffleArray = <T,>(array: T[]): T[] => {
    const shuffled = [...array]
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
    }
    return shuffled
  }

  // 处理答案选择
  const handleAnswerSelect = (answerIndex: number) => {
    if (selectedAnswer !== null || showResult) return
    
    setSelectedAnswer(answerIndex)
    setTotalQuestions(prev => prev + 1)
    
    setTimeout(() => {
      setShowResult(true)
      
      if (answerIndex === currentQuestion?.correctAnswer) {
        setScore(prev => prev + 100)
        setCorrectAnswers(prev => prev + 1)
      }
      
      // 2秒后显示下一题
      setTimeout(() => {
        nextQuestion()
      }, 2000)
    }, 500)
  }

  // 下一题
  const nextQuestion = () => {
    setCurrentQuestion(generateQuestion())
    setSelectedAnswer(null)
    setShowResult(false)
    setQuestionIndex(prev => prev + 1)
  }

  // 游戏计时器
  useEffect(() => {
    if (timeLeft > 0 && !gameOver) {
      const timer = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
      }, 1000)
      return () => clearTimeout(timer)
    } else if (timeLeft === 0) {
      setGameOver(true)
      onGameEnd(score, correctAnswers, totalQuestions)
    }
  }, [timeLeft, gameOver, score, correctAnswers, totalQuestions, onGameEnd])

  // 初始化游戏
  useEffect(() => {
    setCurrentQuestion(generateQuestion())
  }, [targetChar])

  if (gameOver) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="bg-white/90 backdrop-blur-sm rounded-2xl p-8 shadow-lg text-center max-w-md">
          <div className="text-6xl mb-4">🎓</div>
          <h3 className={`${textStyles.sectionTitle} text-gray-800 mb-4`}>
            知识问答结束！
          </h3>
          <div className="space-y-2 mb-6">
            <div className={`${textStyles.tag} text-blue-700`}>
              最终得分: {score}
            </div>
            <div className={`${textStyles.tag} text-green-700`}>
              正确率: {totalQuestions > 0 ? Math.round((correctAnswers / totalQuestions) * 100) : 0}%
            </div>
            <div className={`${textStyles.tag} text-purple-700`}>
              答对题目: {correctAnswers}/{totalQuestions}
            </div>
          </div>
          <button
            onClick={() => window.location.reload()}
            className={`
              ${textStyles.primaryButton} px-6 py-3 
              bg-gradient-to-r from-green-500 to-blue-500 text-white rounded-xl
              hover:from-green-600 hover:to-blue-600 transition-all duration-300
            `}
          >
            再答一次
          </button>
        </div>
      </div>
    )
  }

  if (!currentQuestion) {
    return <div className="h-full flex items-center justify-center">加载中...</div>
  }

  return (
    <div className="h-full flex flex-col">
      {/* 游戏状态栏 */}
      <div className="text-center mb-6">
        <div className="flex justify-center space-x-6 text-sm mb-4">
          <div className="flex items-center space-x-1">
            <span className="text-blue-600">⏰</span>
            <span className={`${textStyles.tag} text-blue-700 font-bold`}>
              {timeLeft}秒
            </span>
          </div>
          <div className="flex items-center space-x-1">
            <span className="text-green-600">🎯</span>
            <span className={`${textStyles.tag} text-green-700 font-bold`}>
              {score}分
            </span>
          </div>
          <div className="flex items-center space-x-1">
            <span className="text-purple-600">📊</span>
            <span className={`${textStyles.tag} text-purple-700 font-bold`}>
              第{questionIndex + 1}题
            </span>
          </div>
        </div>
      </div>

      {/* 问题区域 */}
      <div className="flex-1 flex flex-col items-center justify-center max-w-2xl mx-auto">
        <div className="bg-white/90 backdrop-blur-sm rounded-2xl p-8 shadow-lg w-full">
          <h3 className={`${textStyles.sectionTitle} text-gray-800 mb-8 text-center`}>
            {currentQuestion.question}
          </h3>
          
          <div className="grid grid-cols-2 gap-4">
            {currentQuestion.options.map((option, index) => (
              <button
                key={index}
                onClick={() => handleAnswerSelect(index)}
                disabled={selectedAnswer !== null}
                className={`
                  p-4 rounded-xl text-lg font-medium transition-all duration-300
                  ${selectedAnswer === index
                    ? index === currentQuestion.correctAnswer
                      ? 'bg-green-500 text-white shadow-lg scale-105'
                      : 'bg-red-500 text-white shadow-lg scale-105'
                    : showResult && index === currentQuestion.correctAnswer
                      ? 'bg-green-400 text-white shadow-lg'
                      : 'bg-gray-100 border-2 border-gray-300 text-gray-800 hover:border-blue-400 hover:shadow-md hover:scale-105'
                  }
                  ${selectedAnswer !== null ? 'cursor-not-allowed' : 'cursor-pointer'}
                `}
              >
                {option}
              </button>
            ))}
          </div>
          
          {showResult && (
            <div className="mt-6 p-4 bg-blue-50 rounded-xl">
              <p className={`${textStyles.description} text-blue-800 text-center`}>
                {currentQuestion.explanation}
              </p>
            </div>
          )}
        </div>
      </div>

      {/* 提示信息 */}
      <div className="text-center mt-4">
        <p className={`${textStyles.description} text-gray-600`}>
          {!showResult 
            ? '选择正确答案' 
            : selectedAnswer === currentQuestion.correctAnswer
              ? '🎉 回答正确！'
              : '💡 学到了新知识！'
          }
        </p>
      </div>
    </div>
  )
} 